import store from '@/store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { getToken, setAuthUserInfo, getAuthUserInfo } from '@/utils/auth' // 验权
import { getInfo } from '@/api/login'

const whiteList = ['/login'] // 不重定向白名单


export default ({app})=>{
  app.router.beforeEach((to, from, next) => {
    if(process.browser){
      NProgress.start()
    }
    if (getToken()) {
      if (to.path === '/login') {
        if(process.browser){
          NProgress.done()
        }
        app.router.push('/')
        next()
      } else {
        if(getAuthUserInfo()){
          next()
        }else{
          getInfo(getToken()).then(response => {
            setAuthUserInfo(response.data)
            next()
          }).catch(error => {
            next()
          })
        }

      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        next()
        // next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
        // NProgress.done()
      }
    }
  })


  app.router.onError((error) => {
    const pattern = /Loading chunk (\d)+ failed/g;
    const isChunkLoadFailed = error.message.match(pattern);
    const targetPath = app.router.history.pending.fullPath;
    if (isChunkLoadFailed) {
      app.router.replace(targetPath);
    }
  });

  app.router.afterEach(() => {
    if(process.browser){
      NProgress.done() // 结束Progress
    }
  })
}
